import { Component, OnInit, Output, EventEmitter, ViewChild, Input } from '@angular/core';
import CustomSource from 'devextreme/data/data_source';
import { DxTextBoxComponent, DxTreeViewComponent } from 'devextreme-angular';
import { PurTreeService, TreeItem, TreeItems } from "../pur-tree.service";

@Component({
  selector: 'app-pur-tree',
  templateUrl: './pur-tree.component.html',
  styleUrls: ['./pur-tree.component.css']
})
export class PurTreeComponent implements OnInit {
  // 向上传递所选节点信息
  @Output() onSureOrg: EventEmitter<TreeItem> = new EventEmitter();
  @Input() requestUrl: String = 'v1/api/basicmgmt/organization/list/bidder';
  // 树列表异步数据源
  orgSync: any = {};
  // 树列表同步数据源
  orgItem: Array<TreeItem>
  // 当前选中节点
  currOrgInfo: any;
  orgName: string = '';
  visible: boolean = true;
  loadingVisible: boolean = false;
  // @ViewChild("treeView") tree: DxTreeViewComponent;
  constructor(
    public bidOrgSer: PurTreeService
  ) { }

  ngOnInit() {
    this.initOrgTree();
  }

  initOrgTree(){
    this.orgSync = new CustomSource({
      load: (loadOptions: any) : Promise<TreeItems>  => {
        // console.log(loadOptions);
          // console.log("异步加载"+loadOptions.filter);
          var temp = loadOptions.filter[1]||"";
          return this.bidOrgSer.queryOrgList(temp, "orgId", this.requestUrl)
          .then(res => {
            this.loadingVisible = false;
            return res;
          })
        }
      });
  }

  changeSelection(e){
    this.currOrgInfo = e.node;
  }

  addOrg(){
    if (this.currOrgInfo == undefined || this.currOrgInfo.text == undefined || this.currOrgInfo.key == undefined) {
      this.bidOrgSer.notifyFailMsg("请先选择数据，再执行确认操作！");
      return;
    }
    this.onSureOrg.emit(this.currOrgInfo);
    
  }

  search(){
    if(this.orgName.trim() === ''){
      // 初始化异步树
      this.visible = true;
      this.loadingVisible = true;
      this.orgSync.reload();
      // this.bidOrgSer.notifyFailMsg("请输入查询内容");
      return;
    }
    // console.log(event);
    this.visible = false;
    this.loadingVisible = true;
    this.bidOrgSer.queryOrgList(this.orgName, 'orgName', this.requestUrl)
    .then(res=>{
      this.orgItem = res;
      this.loadingVisible = false;
    })
  }

}
